import { readFile } from 'fs/promises';
import { Plugin } from 'vite';
import path from 'path';

/**
 * Vite插件，用于预处理@iconify/json的图标集数据
 */
export function iconCollectionsPlugin(): Plugin {
  return {
    name: 'icon-collections',
    async resolveId(id) {
      if (id === '@iconify-collections') {
        return id;
      }
      return null;
    },
    async load(id) {
      if (id === '@iconify-collections') {
        try {
          // 读取@iconify/json中的collections.json文件
          const collectionsPath = path.resolve(
            __dirname, '../../node_modules/@iconify/json/collections.json'
          );
          const content = await readFile(collectionsPath, 'utf-8');
          const collections = JSON.parse(content);
          console.log('collections', collections)
          
          collections.forEach((collection, index) => {
            collection.icons = [];
          })
          // 返回处理后的数据
          return `export const collections = ${JSON.stringify(collections)};`;
        } catch (error) {
          console.error('Failed to load icon collections:', error);
          // 返回默认数据作为后备
          return `export const collections = {};`;
        }
      }
      return null;
    },
  };
}